package cn.starrysky108.simpleerp.system.service.impl;

import cn.starrysky108.simpleerp.core.enums.ResultCodeEnum;
import cn.starrysky108.simpleerp.core.exception.StorageException;
import cn.starrysky108.simpleerp.core.properties.SimpleErpProperties;
import cn.starrysky108.simpleerp.core.util.HttpUtil;
import cn.starrysky108.simpleerp.core.util.UploadUtil;
import cn.starrysky108.simpleerp.system.entity.SystemFile;
import cn.starrysky108.simpleerp.system.mapper.SystemFileMapper;
import cn.starrysky108.simpleerp.system.response.UploadResponse;
import cn.starrysky108.simpleerp.system.service.SystemFileService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

/**
 * <p>
 * 资源文件表 服务实现类
 * </p>
 *
 * @author Carl Lee
 */
@Service
public class SystemFileServiceImpl extends ServiceImpl<SystemFileMapper, SystemFile> implements SystemFileService {
    private final Path rootLocation;
    private final String uploadServer;

    @Autowired
    public SystemFileServiceImpl(SimpleErpProperties properties) {
        String dir = UploadUtil.normalize(properties.getUploadDir());
        this.rootLocation = Paths.get(dir);
        this.uploadServer = StringUtils.hasText(properties.getUploadServer()) ? properties.getUploadServer() : HttpUtil.getServerUrl()+"uploads";
    }

    @Override
    public UploadResponse store(MultipartFile file) {
        UploadResponse response = new UploadResponse();
        try {
            String fileName = file.getOriginalFilename();
            if (fileName != null) {
                //根据检查文件是否已经存在
                String md5 = UploadUtil.getMd5(file.getInputStream());
                SystemFile systemFile = getOne(Wrappers.lambdaQuery(SystemFile.class).eq(SystemFile::getMd5, md5));
                if (!ObjectUtils.isEmpty(systemFile)) {
                    //如果数据库中存在该文件，直接返回该文件Id
                    BeanUtils.copyProperties(systemFile, response);
                    return response;
                }
                //新文件地址
                String newFile = UploadUtil.getDestFile(fileName);
                //组合生成存储地址
                Path dest = rootLocation.resolve(newFile);
                //创建文件夹
                UploadUtil.initDirectory(dest);
                //存储文件到目标地址
                Files.copy(file.getInputStream(), dest);
                SystemFile entity = SystemFile.builder()
                        .fileName(fileName)
                        .extension(FilenameUtils.getExtension(fileName))
                        .fileSize(file.getSize())
                        .md5(md5)
                        .type(UploadUtil.getFileType(file.getInputStream()))
                        .path(dest.toString())
                        .url(uploadServer + newFile)
                        .build();
                //存入数据库
                save(entity);
                BeanUtils.copyProperties(entity, response);
                return response;
            }
        } catch (Exception e) {
            throw new StorageException(ResultCodeEnum.FILE_STORE_FAILED, e.getCause(), file.getOriginalFilename());
        }
        return null;
    }

    @Override
    public Stream<Path> loadAll() {
        try {
            return Files.walk(this.rootLocation, 1)
                    .filter(path -> !path.equals(this.rootLocation))
                    .map(this.rootLocation::relativize);
        } catch (IOException e) {
            throw new StorageException(ResultCodeEnum.FILE_LOAD_FAILED, e);
        }

    }


    @Override
    public Resource loadByPath(String path) {
        try {
            Path file = Paths.get(path);
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                throw new StorageException(ResultCodeEnum.FILE_LOAD_FAILED, path);
            }
        } catch (MalformedURLException e) {
            throw new StorageException(ResultCodeEnum.FILE_LOAD_FAILED, e, path);
        }
    }

    @Override
    public Resource loadById(Long fileId) {
        SystemFile systemFile = getOne(Wrappers.lambdaQuery(SystemFile.class).eq(SystemFile::getId, fileId));
        if (ObjectUtils.isEmpty(systemFile)) {
            throw new StorageException(ResultCodeEnum.FILE_LOAD_FAILED, String.valueOf(fileId));
        }

        return loadByPath(systemFile.getPath());
    }


    @Override
    public void deleteAll() {
        FileSystemUtils.deleteRecursively(rootLocation.toFile());
    }

    @Override
    public Boolean delete(Long fileId) {
        SystemFile file = getById(fileId);
        if (ObjectUtils.isEmpty(file)) {
            return false;
        }
        removeById(file);
        //文件不被其他引用时删除文件
        if (!file.getUsed()) {
            FileSystemUtils.deleteRecursively(new File(file.getPath()));
        }
        return true;
    }
}
